package com.chinamsp.baisc.util;

import java.io.IOException;

import org.springframework.util.StringUtils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * json 工具类
 * 
 * @author shifenghu
 * @version 1.0
 */
public class JSONUtils {

	/**
	 * 将 json 解析成字符串
	 * @param obj
	 * @return
	 */
	public static String toJSON(Object obj) {
		if (obj == null) {
			return null;
		}
		try {
			return newObjectMap().writeValueAsString(obj);
		} catch (JsonProcessingException e) {
			throw new IllegalArgumentException(e);
		}
	}
	
	/**
	 * 将 字符串解析成 bean
	 * @param clazz
	 * @param json
	 * @return
	 */
	public static <T> T parse(Class<T> clazz, String json) {
		try {
			if (StringUtils.isEmpty(json) || clazz == null) {
				return null;
			}
			return newObjectMap().readValue(json, clazz);
		} catch (IOException e) {
			throw new IllegalArgumentException(e);
		}
	}

	/**
	 * 初始化一个 obj map
	 * 
	 * @return
	 */
	private static ObjectMapper newObjectMap() {
		ObjectMapper mapper = new ObjectMapper();
		mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
		return mapper;
	}
}
